<template>
  <div class="app-container">
    <el-form class="alone-business" :model="queryData" ref="queryDataRef" :inline="true" label-width="68px">
      <el-form-item label="渠道名称" prop="channelName">
        <el-input v-model="queryData.channelName" placeholder="请输入姓名或者手机号" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="渠道性质" prop="channelNature">
        <el-select v-model="queryData.channelNature" placeholder="请选择" clearable style="width: 200px">
          <el-option :value="1" label="内部市场人员"></el-option>
          <el-option :value="2" label="外部渠道"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道类型" prop="channelType">
        <el-select v-model="queryData.channelType" placeholder="请选择" clearable style="width: 200px">
          <el-option :value="1" label="培训机构"></el-option>
          <el-option :value="2" label="共享展厅"></el-option>
          <el-option :value="99" label="其他"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道等级" prop="channelLevel">
        <el-select v-model="queryData.channelLevel" placeholder="请选择" clearable style="width: 200px">
          <el-option :value="1" label="一级渠道"></el-option>
          <el-option :value="2" label="次级渠道"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" plain icon="Plus" @click="openMarketing('')">添加一级渠道</el-button>
      <el-button type="info" plain :loading="downLoading" @click="handleExport">导出</el-button>
    </el-row>
    <el-table v-loading="tableLoading" :data="tableData" highlight-current-row style="width: 100%; margin-top: 20px">
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column property="channelName" label="渠道名称" width="180" />
      <el-table-column property="channelNatureStr" label="渠道性质" width="120" />
      <el-table-column property="channelTypeStr" label="渠道类型" />
      <el-table-column property="channelLevelStr" label="渠道等级" width="120" />
      <el-table-column property="belongRootChannelName" label="所谓一级渠道" width="120" />
      <el-table-column property="phoneNumber" label="手机号" width="160" />
      <el-table-column property="thisChannelAmount" label="累计返佣获利" width="120" />
      <el-table-column property="nextChannelCount" label="绑定渠道数量" width="120" />
      <el-table-column property="nextChannelAmount" label="渠道累计返佣获利" width="160" />
      <el-table-column property="businessCount" label="绑定商家数量" width="120" />
      <el-table-column property="businessBuyAmount" label="商家累计采购金额" width="160" />
      <el-table-column property="businessCommissionAmount" label="商家累计返佣获利" width="160" />
      <el-table-column property="createBy" label="创建人" width="120" />
      <el-table-column property="createTime" label="创建日期" width="120" />
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="scope">
          <el-button link type="primary" @click="openMarketing(scope.row)"> 编辑 </el-button>
          <el-button v-if="scope.row.hasBusiness" link type="primary" @click="toPath(scope.row, 'channel/customer')">
            管理客户
          </el-button>
          <el-button
            v-if="scope.row.hasNextChannel"
            link
            type="primary"
            @click="toPath(scope.row, `channel/lowerLevel/${scope.row.channelTenantId}`)"
          >
            管理下级
          </el-button>
          <!-- <el-button link type="info" disabled @click="toPath(scope.row, 'channel/lowerLevel/1')"> 管理下级 </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="listTotal" v-model:page="queryData.current" v-model:limit="queryData.size" @pagination="getTable" />

    <!-- 添加/编辑渠道 抽屉 -->
    <el-drawer
      title="添加渠道"
      v-model="channelDrawer"
      @close="closeChannel(channelFormRef)"
      size="600px"
      append-to-body
      class="rebate-rules-drawer"
    >
      <div class="spase">
        <el-scrollbar max-height="calc(100vh - 90px)">
          <!-- 查看编辑 显示 -->
          <template v-if="channelForm.channelTenantId">
            <!-- <el-row class="info-tips" justify="space-between">
              <div>会员信息：</div>
            </el-row> -->
            <div class="info-drawer" v-if="channelForm.orgType == 2">
              <img class="img-icon" alt="" src="@/assets/images/products/personal_icon.png" />
              <div class="info-item">
                <el-row style="margin-bottom: 10px">
                  <div class="label">姓名</div>
                  <div class="text">{{ channelForm.personName }}</div>
                </el-row>
                <el-row>
                  <div class="label">手机号</div>
                  <div class="text">{{ channelForm.personCode }}</div>
                </el-row>
              </div>
            </div>
            <div class="info-drawer" v-if="channelForm.orgType == 1">
              <el-row justify="space-between">
                <img class="img-icon" alt="" src="@/assets/images/products/mechanism_icon.png" />
                <div class="img-text">如果是“机构”身份，后续绑定对公账户，佣金将发放到公账户</div>
              </el-row>
              <div class="info-item">
                <el-row style="margin-bottom: 10px">
                  <div class="label">机构名称</div>
                  <div class="text">{{ channelForm.orgName }}</div>
                </el-row>
                <el-row style="margin-bottom: 10px">
                  <div class="label">信用代码</div>
                  <div class="text">{{ channelForm.socialCodeId }}</div>
                </el-row>
                <el-row>
                  <div class="label">管理员手机号</div>
                  <div class="text">{{ channelForm.account }}</div>
                </el-row>
              </div>
            </div>
          </template>
          <el-form
            style="width: 100%"
            ref="channelFormRef"
            :model="channelForm"
            :rules="channelRules"
            label-position="top"
            label-width="80px"
          >
            <!-- 新增 显示 -->
            <template v-if="!channelForm.channelTenantId">
              <el-form-item prop="orgType">
                <!-- <template #label>
                  会员信息
                  <el-text v-if="channelForm.info == 2" type="info" size="small"
                    >（如选择“机构”身份，后续绑定对公账户，佣金将发放到公账户)</el-text
                  >
                </template> -->
                <el-radio-group v-model="channelForm.orgType">
                  <el-radio :value="2">个人</el-radio>
                  <el-radio :value="1">机构</el-radio>
                </el-radio-group>
              </el-form-item>
              <template v-if="channelForm.orgType == 2">
                <el-form-item label="姓名" prop="personName">
                  <el-input v-model="channelForm.personName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="手机号" prop="personCode">
                  <el-input v-model="channelForm.personCode" placeholder="请输入手机号" maxlength="11" />
                </el-form-item>
              </template>
              <template v-if="channelForm.orgType == 1">
                <el-form-item label="机构名称" prop="orgName">
                  <el-input v-model="channelForm.orgName" placeholder="请输入机构名称" />
                </el-form-item>
                <el-form-item label="营业执照编码" prop="socialCodeId">
                  <el-input v-model="channelForm.socialCodeId" placeholder="请输入营业执照编码" />
                </el-form-item>
                <el-form-item label="管理员手机号" prop="account">
                  <el-input v-model="channelForm.account" placeholder="请输入" maxlength="11" />
                </el-form-item>
              </template>
            </template>

            <el-form-item label="渠道性质" prop="channelNature">
              <el-radio-group v-model="channelForm.channelNature" :disabled="channelForm.channelTenantId">
                <el-radio :value="1">内部市场人员</el-radio>
                <el-radio :value="2">外部渠道</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="渠道类型" prop="channelType" v-if="channelForm.channelNature == 2">
              <el-radio-group v-model="channelForm.channelType" :disabled="channelForm.channelTenantId">
                <el-radio :value="1">培训结构</el-radio>
                <el-radio :value="2">共享展厅</el-radio>
                <el-radio :value="99">其他</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="所在城市" prop="cityId">
              <el-cascader
                v-model="channelForm.cityId"
                :options="areaOptions"
                :props="areaProps"
                filterable
                :disabled="!isChannelEdit"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeChannel(channelFormRef)">取 消</el-button>
          <el-button
            class="btn"
            v-if="isChannelEdit"
            :loading="marketingBtn"
            type="primary"
            @click="submitChannel(channelFormRef)"
            >确 定</el-button
          >
          <el-button class="btn" v-else type="primary" @click="isChannelEdit = true">编 辑</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
import { getArea } from "@/api/tenant";
import { channelPage, addFirstLevel, channelDetail, edit, manageExport } from "@/api/system/rebateRules/channel/index";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

defineOptions({
  name: "Channel"
});

// 搜索条件
const queryData = ref({});
// 商家表格总数
const listTotal = ref(0);

// 查询
const searchData = () => {
  getTable();
};

// 搜索重置
const reset = () => {
  queryData.value = {
    channelName: "",
    channelNature: "",
    channelType: "",
    channelLevel: "",
    current: 1,
    size: 10
  };
  getTable();
};

// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);

// 跳转页面
const toPath = (row, path) => {
  router.push({
    path,
    query: {
      channelTenantId: row.channelTenantId,
      channelName: row.channelName
    }
  });
};

const channelDrawer = ref(false);
const channelForm = ref({});
const channelRules = {
  personName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  personCode: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号输入错误", trigger: "blur" }
  ],
  orgName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  socialCodeId: [{ required: true, message: "请输入营业执照编码", trigger: "blur" }],
  account: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号输入错误", trigger: "blur" }
  ],
  channelNature: [{ required: true, message: "请选择渠道性质", trigger: "change" }],
  channelType: [{ required: true, message: "请选择渠道类型", trigger: "change" }],
  cityId: [{ required: true, message: "请选择所在城市", trigger: "change" }]
};

const areaOptions = ref([]);
const areaProps = {
  value: "id",
  label: "name"
};
const channelFormRef = ref();
const marketingBtn = ref(false);
// 是否可编辑
const isChannelEdit = ref(true);

// 是否点击过表格操作按钮编辑
const editStart = ref(false);
// 打开营销返佣抽屉
const openMarketing = row => {
  channelForm.value = {
    orgType: 2
  };
  channelDrawer.value = true;
  isChannelEdit.value = true;
  editStart.value = false;
  getAreaApi();
  if (row) {
    channelForm.value = {};
    channelDetail(row.channelTenantId).then(res => {
      console.log(res);
      channelForm.value = res.data;
    });
    isChannelEdit.value = false;
    editStart.value = true;
  }
};
// 关闭营销抽屉
const closeChannel = formRef => {
  if (!formRef) return;
  channelDrawer.value = false;
  channelForm.value = {};
  marketingBtn.value = false;
  formRef.resetFields();
};
// 提交营销设置
const submitChannel = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      let postData = { ...channelForm.value };
      marketingBtn.value = true;
      if (!editStart.value) {
        postData.cityId = postData.cityId[2];
        addFirstLevel(postData)
          .then(res => {
            ElMessage.success("添加成功");
            closeChannel(channelFormRef.value);
            getTable();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      } else {
        if (postData.cityId instanceof Array) {
          postData.cityId = postData.cityId[2];
        }
        edit(postData)
          .then(res => {
            ElMessage.success("编辑成功");
            closeChannel(channelFormRef.value);
            getTable();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取地址
const getAreaApi = () => {
  getArea().then(res => {
    areaOptions.value = res.data;
  });
};

// 获取列表数据
const getTable = () => {
  tableLoading.value = true;
  channelPage(queryData.value).then(res => {
    tableData.value = res.data.list;
    listTotal.value = res.data.total;
    tableLoading.value = false;
  });
};

const downLoading = ref(false);
/** 导出按钮操作 */
const handleExport = () => {
  downLoading.value = true;
  manageExport(queryData.value)
    .then(res => {
      proxy.getFileDownload(res, `渠道管理${new Date().getTime()}.xlsx`);
    })
    .finally(() => {
      downLoading.value = false;
    });
};

onMounted(() => {
  getTable();
});
</script>
<style lang="scss" scoped>
.info-tips {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 20px;
}
.form-tips {
  margin-bottom: 20px;
  font-size: 14px;
  color: #ea0000;
}
.rebate-rules-drawer {
  .info-drawer {
    .img-icon {
      display: block;
      width: 84px;
      height: 24px;
    }
    .img-text {
      font-size: 12px;
      color: #86909c;
      line-height: 24px;
    }
    .info-item {
      // width: 435px;
      width: 100%;
      border-radius: 0px 4px 4px 4px;
      border: 1px solid #e5e8ef;
      padding: 10px 15px;
      margin-bottom: 20px;
      .label {
        font-size: 14px;
        color: #86909c;
        width: 100px;
      }
      .text {
        font-size: 14px;
        color: #3d3d3d;
      }
    }
  }

  .btn {
    width: 120px;
    height: 36px;
    line-height: 36px;
  }
}
</style>
<style lang="scss">
.rebate-rules-drawer {
  .el-drawer__header {
    margin-bottom: 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #dcdfe6;
  }
}
</style>
